import rea from './rea'
import util from './util'
/**
 * 游戏基础的精灵类
 */
export default class Sprite {
  constructor(imgSrc = '', width = 0, height = 0, x = 0, y = 0, z = 1, custom = null, uuid = null) {
    this.imgSrc = imgSrc
    if (custom)
      this.customUpdate(custom, uuid)
    else{
      this.img = wx.createImage()
      this.__setUUID(uuid)
      this.img.src = imgSrc
    }
    this.width = width
    this.height = height

    this.x = x
    this.y = y
    this.z = z
    this.update_tick = 0
    this.visible = true
  }

  __setUUID(uuid){
    this.img.uuid = uuid
    if (!this.img.uuid)
      this.img.uuid = rea.generateUUID()
  }

  clear(ctx){
    this.visible = false
    ctx.clearImage(this.img)
  }

  __tryForceUpdateImage(cvs, uuid){
    if (!this.update_tick){
      if (!this.img){
        this.img = wx.createImage()
        this.__setUUID(uuid)
      }else{
        let uid = this.img.uuid
        this.img = wx.createImage()  //ios will not trig onload for the same image
        this.__setUUID(uid)
      }
      this.img.onload = e => {
        this.force_update = true
      }
      this.img.src = cvs.toDataURL()
    }
  }

  customUpdate(custom, uuid){
    let img = wx.createImage()
    img.onload = e => {
      let cvs = wx.createCanvas()
      let ctx = cvs.getContext('2d')
      cvs.width = this.width
      cvs.height = this.height
      ctx.drawImage(img, custom.sx, custom.sy, custom.sw, custom.sh, 0, 0, this.width, this.height)
      let texts = custom.texts
      //
      for (let i in texts){
        if (texts[i].src){
          let icon = wx.createImage()
          this.update_tick++
          icon.onload = e => {
            this.update_tick--
            ctx.drawImage(icon, 0, 0, icon.width, icon.height, texts[i].pos[0], texts[i].pos[1], texts[i].pos[2], texts[i].pos[3])
            this.__tryForceUpdateImage(cvs, uuid)
          }
          icon.src = texts[i].src
        }else{
          ctx.fillStyle = texts[i].color
          ctx.font = texts[i].font
          ctx.fillText(texts[i].value, texts[i].pos[0], texts[i].pos[1])
        }
      }
      this.__tryForceUpdateImage(cvs, uuid)
    }
    img.src = this.imgSrc
  }
  /**
   * 将精灵图绘制在canvas上
   */
  async drawToCanvas(ctx, newTexture = false) {
    if (!this.visible || !this.img) return
    let frs = this.force_update
    this.force_update = false
    await ctx.drawImage0(
      this.img,
      this.x,
      this.y,
      this.width,
      this.height,
      this.z,
      frs,
      newTexture
    )
  }

  /**
   * 简单的碰撞检测定义：
   * 另一个精灵的中心点处于本精灵所在的矩形内即可
   * @param{Sprite} sp: Sptite的实例
   */
  isCollideWith(sp) {
    const spX = sp.x + sp.width / 2
    const spY = sp.y + sp.height / 2

    if (!this.visible || !sp.visible) return false

    return this.pointIsIn(spX, spY)
  }

  pointIsIn(aX, aY){
    return !!(aX >= this.x
      && aX <= this.x + this.width
      && aY >= this.y
      && aY <= this.y + this.height)
  }
}
